package com.sali.controller;


import com.sali.service.SaliUploadLocalService;
import com.sali.service.SaliUploadOssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@Controller
public class UploadController {

    @Autowired
    private SaliUploadLocalService uploadService;

    @Autowired
    private SaliUploadOssService saliUploadOssService;


    /**
     * 文件上传具体实现
     */
    @PostMapping("/upload/file-local")
    @ResponseBody
    public Map<String, Object> uploadFileLocal(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) {
        if (multipartFile.isEmpty()) {
            return null;
        }
        long size = multipartFile.getSize();
        String originalFilename = multipartFile.getOriginalFilename();
        String contentType = multipartFile.getContentType();//imgae/png;image/jpg;image/gif
//        if(!contentType.equals("png|jpg|gif")){
//            return "文件类型不正确";
//        }
        // 1: 获取用户指定的文件夹。问这个文件夹为什么要从页面上传递过来呢?
        // 原因是：做隔离，不同业务，不同文件放在不同的目录中
        String dir = request.getParameter("dir");
        return uploadService.uploadImgMap(multipartFile, dir);
    }

    /**
     * 文件上传具体实现
     *
     * @param multipartFile
     * @param request
     * @return
     */
    @PostMapping("/upload/file-oss")
    @ResponseBody
    public Map<String, Object> upload(@RequestParam("file") MultipartFile multipartFile, HttpServletRequest request) {
        String dir = request.getParameter("dir");
        Map<String, Object> map = new HashMap<>();
        map.put("url", saliUploadOssService.uploadfile(multipartFile, dir));
        return map;
    }

}
